#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Project          :beginning-python
# @FileName         :sunspots_roto.py
# @IDE              :PyCharm     
# @Time             :2022/5/30 16:22
# @Author           :Kermit Lee
# ==============================================

import json
from urllib import request
from reportlab.graphics.shapes import *
from reportlab.graphics.charts.lineplots import LinePlot
from reportlab.graphics.charts.textlabels import Label
from reportlab.graphics import renderPDF

URL = 'https://services.swpc.noaa.gov/json/solar-cycle/predicted-solar-cycle.json'

data_json = json.loads(request.urlopen(URL).readlines()[0].decode())
# print(type(data_json[0]), data_json[0])
data = []
for d in data_json:
    t = []
    for k, v in d.items():
        if k == 'time-tag': t.extend([float(n) for n in v.split('-')])
        else: t.append(float(v))
    data.append(t)

pred = [row[2] for row in data]
high = [row[3] for row in data]
low = [row[4] for row in data]
times = [row[0] + row[1]/12.0 for row in data]

drawing = Drawing(400, 200)
lp = LinePlot()
lp.x = 50
lp.y = 50
lp.height = 125
lp.width = 300
lp.data = [tuple(zip(times, pred)), tuple(zip(times, high)), tuple(zip(times, low))]
lp.lines[0].strokeColor = colors.blue
lp.lines[1].strokeColor = colors.red
lp.lines[2].strokeColor = colors.green

drawing.add(lp)

drawing.add(String(250, 150, 'Sunspots', fontSize=14, fillColor=colors.red))

renderPDF.drawToFile(drawing, 'report2.pdf', 'Sunspots')

# if __name__ == '__main__':
#     pass
